/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package me.tisoft.springphpview.viewresolver;

import com.googlecode.fcgi4j.FCGIConnection;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.View;

/**
 *
 * @author taleh
 */
public class PhpFastcgiViewRenderer implements View {

    FCGIConnection connection;

    public PhpFastcgiViewRenderer(FCGIConnection connection) {
        this.connection = connection;
    }

    @Override
    public String getContentType() {
        return "text/html";
    }

    private String implodeMapToPostData(Map<String, Object> map) {
        String ret = "";
        Iterator<Map.Entry<String, Object>> iteratorset = map.entrySet().iterator();
        for (int i = 0; i < map.size(); i++) {
            Map.Entry<String, Object> entry = iteratorset.next();
            ret += entry.getKey() + "=" + entry.getValue() + "&";
        }

        return ret;
    }

    @Override
    public void render(Map<String, ?> map, HttpServletRequest request, HttpServletResponse response) throws Exception {

        LayoutModelView mav = (LayoutModelView) map.get("layoutModelView");

        if (mav != null) {
            connection.setQueryString("layout=" + mav.getLayout() + "&view=" + mav.getViewName());
            if (mav.getModel() != null) {
                byte[] postData = this.implodeMapToPostData(mav.getModel()).getBytes();
                connection.setContentLength(postData.length);
                connection.write(ByteBuffer.wrap(postData));
            }
        }

//        Map<String, String> responseHeaders = connection.getResponseHeaders();
//        for (String key : responseHeaders.keySet()) {
//            System.out.println("HTTP HEADER: " + key + "->" + responseHeaders.get(key));
//        }
//read response data
        ByteBuffer buffer = ByteBuffer.allocate(10240);
        connection.read(buffer);
        connection.close();

        buffer.flip();

        final byte[] data = new byte[buffer.remaining()];
        buffer.get(data);
        response.getWriter().write(new String(data));

    }
}
